package com.lhoverc.service.log.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lhoverc.mapper.LogMapper;
import com.lhoverc.mapper.UserMapper;
import com.lhoverc.pojo.PageBean;
import com.lhoverc.pojo.VO.LogVO;
import com.lhoverc.pojo.entity.LogEntity;
import com.lhoverc.service.log.LogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: LiCheng
 * @CreateTime: 2025-04-27
 * @Description:
 * @Version: 1.0
 */
@Slf4j
@Service
public class logServiceImpl implements LogService {
    @Autowired
    private LogMapper logMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public PageBean getLogPage(String operatorName, String returnValue, Integer page, Integer pageSize, LocalDate operationTime) {
        // 1. 设置分页参数
        PageHelper.startPage(page, pageSize);

        // 2. 执行查询（包含所有过滤条件）
        LocalDateTime operationTimeStart = null;
        LocalDateTime operationTimeEnd = null;
        if (operationTime != null) {
            operationTimeStart = operationTime.atStartOfDay();
            operationTimeEnd = operationTime.atTime(LocalTime.MAX);
        }
//        List<LogEntity> logEntityList = logMapper.getLogs(returnValue, operationTimeStart, operationTimeEnd);
//        log.info("logEntityList:{}", logEntityList.toArray().length);
//        List<Integer> userIds = userMapper.getIdByUsername(operatorName);
//        // 3. 转换实体
//        List<LogVO> voList = new ArrayList<>();
//        for (LogEntity logEntity : logEntityList) {
//            if (userIds.contains(logEntity.getId())) {
//                LogVO vo = new LogVO();
//                BeanUtils.copyProperties(logEntity, vo);
//                vo.setOperatorName(userMapper.getUsernameById(logEntity.getId()));
//                voList.add(vo);
//            }
//        }
//        log.info("voList:{}", voList.toArray().length);

        List<LogVO> voList = logMapper.getLogs(operatorName, returnValue, operationTimeStart, operationTimeEnd);
        // 4. 获取分页信息
        PageInfo<LogVO> pageInfo = new PageInfo<>(voList);
        // 5. 返回正确分页结果
        return new PageBean(pageInfo.getTotal(), voList);
    }
}
